import * as echarts from "echarts";

import {onMounted, ref, shallowRef} from 'vue'

// import elementResizeDetectorMaker from 'element-resize-detector'

/**
 * @description 使用Echarts(只是为了添加图表响应式)
 * @param {Element} data 数据 目前只针对于项目里一些data都是写死在options 所以data为可选 根据项目自行修改即可
 * @param {Object} options 绘制Echarts的参数(必传)
 * @return chart
 * */
export const useEcharts = (options: echarts.EChartsCoreOption, data?: any) => {
	const myChart = shallowRef<echarts.EChartsType>();
	const echartsRef = shallowRef<HTMLDivElement>(null);

    const echartsResize = () => {
        echartsRef && myChart?.value?.resize();
    };
    
	// onMounted(() => {
	// 	if (data?.length !== 0) {
	// 		myChart?.value?.setOption(options);
	// 	}
	// });

	onMounted(() => {
		if (data?.length !== 0) {
			myChart?.value?.setOption(options);
		}

		if (echartsRef?.value) {
			myChart.value = echarts.init(echartsRef.value as HTMLDivElement);
		}
		myChart?.value?.setOption(options);

		window.addEventListener("resize", echartsResize, false);
		return () => {
			window.removeEventListener("resize", echartsResize);
			myChart?.value?.dispose();
		};
	});

	return [echartsRef, myChart];
};